from flask import current_app


class APScheduler(object):

    def add_job(self, jobid, func, args, **kwargs):
        """

        添加任务

        :param func:
        :param jobid:
        :param args: 元祖 -> (1，2)

        :param jobstore: 存储位置

        :param trigger:

        data -> run_date datetime表达式

        cron -> second/minute/day_of_week

        interval -> seconds 延迟时间

        next_run_time -> datetime.datetime.now() + datetime.timedelta(seconds=12))

        :return:

        """

        job_def = dict(self.get_dict(kwargs))

        job_def['id'] = str(jobid)

        job_def['func'] = func

        job_def['args'] = args
        job_def = self.fix_job_def(job_def)
        # 判断是否存在这个jobid
        # self.remove_job(jobid)  # 删除原job
        job = self.get_job(jobid)
        if not job:
            current_app.apscheduler.add_job(**job_def)
        self.resume_job(jobid)

    def remove_job(self, jobid, jobstore=None):
        """删除任务"""

        current_app.apscheduler.remove_job(jobid, jobstore=jobstore)

    @staticmethod
    def resume_job(jobid, jobstore=None):
        """恢复任务"""

        current_app.apscheduler.resume_job(str(jobid), jobstore=jobstore)

    @staticmethod
    def pause_job(jobid, jobstore=None):
        """暂停任务"""

        current_app.apscheduler.pause_job(str(jobid), jobstore=jobstore)

    @staticmethod
    def get_job(job_id):
        job = current_app.apscheduler.get_job(id=str(job_id))
        return job

    @staticmethod
    def reschedule_job(jobid, minute, trigger='interval'):
        current_app.apscheduler.reschedule_job(str(jobid), trigger=trigger,
                                               seconds=minute * 60 if minute <= 0 else 60 * 60 * 24)

    @staticmethod
    def fix_job_def(job_def):
        """维修job工程"""

        if job_def.get('trigger') == 'date':

            job_def['run_date'] = job_def.get('run_date') or None

        elif job_def.get('trigger') == 'cron':

            job_def['hour'] = job_def.get('hour') or "*"

            job_def['minute'] = job_def.get('minute') or "*"

            job_def['week'] = job_def.get('week') or "*"

            job_def['day'] = job_def.get('day') or "*"

            job_def['month'] = job_def.get('month') or "*"

        elif job_def.get('trigger') == 'interval':

            job_def['seconds'] = job_def.get('execute_time') * 60 or 60 * 60 * 24

        # job_def['next_run_time'] = job_def.get('next_run_time') or None
        job_def.pop('execute_time')
        return job_def

    @staticmethod
    def get_dict(model):
        o = model['kwargs']
        if hasattr(o, 'keys') and hasattr(o, '__getitem__'):
            o.set_keys(['trigger', "execute_time"])
            return dict(o)
        return model
